#include "configdialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QFileDialog>
#include <QColorDialog>
#include <QFontComboBox>
#include <QSlider>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QTextEdit>
#include <QGroupBox>
#include <QRadioButton>
#include <QIntValidator>
#include <QRegularExpressionValidator>

ConfigDialog::ConfigDialog(QWidget *parent)
    : QDialog(parent)
    , m_mode("create")
{
    setWindowTitle("SSH Configuration");
    setModal(true);
    resize(600, 500);

    createUI();
    loadSettings();
}

ConfigDialog::~ConfigDialog()
{
}

void ConfigDialog::setProfile(const ConnectionManager::ConnectionProfile &profile)
{
    m_nameEdit->setText(profile.name);
    m_hostEdit->setText(profile.host);
    m_portSpin->setValue(profile.port);
    m_usernameEdit->setText(profile.username);
    m_passwordEdit->setText(profile.password);
    m_privateKeyEdit->setText(profile.privateKeyPath);
    m_descriptionEdit->setText(profile.description);
    m_groupCombo->setCurrentText(profile.group);
    m_favoriteCheck->setChecked(profile.isFavorite);

    // 高级设置
    m_timeoutSpin->setValue(30);
    m_keepAliveCheck->setChecked(true);
    m_keepAliveIntervalSpin->setValue(30);
    m_compressionCheck->setChecked(false);
    m_terminalTypeCombo->setCurrentText("xterm-256color");

    updateAuthMethodUI();
}

ConnectionManager::ConnectionProfile ConfigDialog::getProfile() const
{
    ConnectionManager::ConnectionProfile profile;
    profile.name = m_nameEdit->text().trimmed();
    profile.host = m_hostEdit->text().trimmed();
    profile.port = m_portSpin->value();
    profile.username = m_usernameEdit->text().trimmed();
    profile.password = m_passwordEdit->text();
    profile.privateKeyPath = m_privateKeyEdit->text().trimmed();
    profile.description = m_descriptionEdit->toPlainText().trimmed();
    profile.group = m_groupCombo->currentText();
    profile.isFavorite = m_favoriteCheck->isChecked();

    return profile;
}

void ConfigDialog::setMode(const QString &mode)
{
    m_mode = mode;
    if (mode == "create") {
        setWindowTitle("New SSH Connection");
        resetSettings();
    } else if (mode == "edit") {
        setWindowTitle("Edit SSH Connection");
    }
}

bool ConfigDialog::validateInput() const
{
    return validateBasicSettings();
}

void ConfigDialog::browsePrivateKey()
{
    QString filePath = QFileDialog::getOpenFileName(
        this,
        "Select Private Key",
        QString(),
        "Private Key Files (*.pem *.key *.ppk);;All Files (*.*)"
    );

    if (!filePath.isEmpty()) {
        m_privateKeyEdit->setText(filePath);
    }
}

void ConfigDialog::testConnection()
{
    if (!validateInput()) {
        return;
    }

    ConnectionManager::ConnectionProfile profile = getProfile();
    emit testConnectionRequested(profile);
}

void ConfigDialog::saveProfile()
{
    if (!validateInput()) {
        return;
    }

    ConnectionManager::ConnectionProfile profile = getProfile();

    if (m_mode == "create") {
        emit profileCreated(profile);
    } else if (m_mode == "edit") {
        emit profileUpdated(profile);
    }

    accept();
}

void ConfigDialog::resetToDefaults()
{
    resetSettings();
}

void ConfigDialog::onAuthMethodChanged()
{
    updateAuthMethodUI();
}

void ConfigDialog::onAdvancedSettingsChanged()
{
    // 处理高级设置变更
}

void ConfigDialog::updatePasswordStrength()
{
    QString password = m_passwordEdit->text();
    // 简化的密码强度检查
    int strength = 0;
    if (password.length() >= 8) strength++;
    if (password.length() >= 12) strength++;
    if (password.contains(QRegularExpression("[A-Z]"))) strength++;
    if (password.contains(QRegularExpression("[a-z]"))) strength++;
    if (password.contains(QRegularExpression("[0-9]"))) strength++;
    if (password.contains(QRegularExpression("[^A-Za-z0-9]"))) strength++;

    // 更新密码强度显示（如果有相关UI元素）
}

void ConfigDialog::generateKeyPair()
{
    QMessageBox::information(this, "Generate Key Pair",
                             "Key pair generation is not implemented yet.\n"
                             "Please use ssh-keygen or another tool to generate keys.");
}

void ConfigDialog::checkConnection()
{
    testConnection();
}

void ConfigDialog::createUI()
{
    m_tabWidget = new QTabWidget(this);

    // 创建各个标签页
    createBasicSettingsTab();
    createAdvancedSettingsTab();
    createTerminalSettingsTab();
    createAppearanceSettingsTab();

    // 创建按钮
    createButtons();

    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_tabWidget);
    mainLayout->addLayout(createButtonsLayout());

    setLayout(mainLayout);
}

void ConfigDialog::createBasicSettingsTab()
{
    QWidget *basicWidget = new QWidget();
    QVBoxLayout *basicLayout = new QVBoxLayout(basicWidget);

    // 基本设置表单
    QFormLayout *formLayout = new QFormLayout();

    // 配置名称
    m_nameEdit = new QLineEdit(this);
    m_nameEdit->setPlaceholderText("Enter profile name");
    formLayout->addRow("Profile Name:", m_nameEdit);

    // 主机地址
    m_hostEdit = new QLineEdit(this);
    m_hostEdit->setPlaceholderText("Enter hostname or IP address");
    formLayout->addRow("Host:", m_hostEdit);

    // 端口
    m_portSpin = new QSpinBox(this);
    m_portSpin->setRange(1, 65535);
    m_portSpin->setValue(22);
    formLayout->addRow("Port:", m_portSpin);

    // 用户名
    m_usernameEdit = new QLineEdit(this);
    m_usernameEdit->setPlaceholderText("Enter username");
    formLayout->addRow("Username:", m_usernameEdit);

    // 认证方法
    m_authMethodCombo = new QComboBox(this);
    m_authMethodCombo->addItem("Password");
    m_authMethodCombo->addItem("Public Key");
    m_authMethodCombo->addItem("SSH Agent");
    connect(m_authMethodCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onAuthMethodChanged()));
    formLayout->addRow("Authentication:", m_authMethodCombo);

    // 密码
    m_passwordEdit = new QLineEdit(this);
    m_passwordEdit->setEchoMode(QLineEdit::Password);
    m_passwordEdit->setPlaceholderText("Enter password");
    connect(m_passwordEdit, SIGNAL(textChanged(QString)), this, SLOT(updatePasswordStrength()));
    formLayout->addRow("Password:", m_passwordEdit);

    // 私钥文件
    QHBoxLayout *keyLayout = new QHBoxLayout();
    m_privateKeyEdit = new QLineEdit(this);
    m_privateKeyEdit->setPlaceholderText("Path to private key file");
    m_browseKeyButton = new QPushButton("Browse...", this);
    connect(m_browseKeyButton, SIGNAL(clicked()), this, SLOT(browsePrivateKey()));
    keyLayout->addWidget(m_privateKeyEdit);
    keyLayout->addWidget(m_browseKeyButton);
    formLayout->addRow("Private Key:", keyLayout);

    // 密码短语
    m_passphraseEdit = new QLineEdit(this);
    m_passphraseEdit->setEchoMode(QLineEdit::Password);
    m_passphraseEdit->setPlaceholderText("Enter passphrase (optional)");
    formLayout->addRow("Passphrase:", m_passphraseEdit);

    // 组
    m_groupCombo = new QComboBox(this);
    m_groupCombo->setEditable(true);
    m_groupCombo->addItems(QStringList() << "Default" << "Servers" << "Work" << "Personal");
    formLayout->addRow("Group:", m_groupCombo);

    // 描述
    m_descriptionEdit = new QTextEdit(this);
    m_descriptionEdit->setMaximumHeight(60);
    m_descriptionEdit->setPlaceholderText("Enter description (optional)");
    formLayout->addRow("Description:", m_descriptionEdit);

    // 收藏
    m_favoriteCheck = new QCheckBox("Add to favorites", this);
    formLayout->addRow("", m_favoriteCheck);

    basicLayout->addLayout(formLayout);
    basicLayout->addStretch();

    m_tabWidget->addTab(basicWidget, "Basic");
}

void ConfigDialog::createAdvancedSettingsTab()
{
    QWidget *advancedWidget = new QWidget();
    QVBoxLayout *advancedLayout = new QVBoxLayout(advancedWidget);

    QFormLayout *formLayout = new QFormLayout();

    // 连接超时
    m_timeoutSpin = new QSpinBox(this);
    m_timeoutSpin->setRange(5, 300);
    m_timeoutSpin->setValue(30);
    m_timeoutSpin->setSuffix(" seconds");
    formLayout->addRow("Connection Timeout:", m_timeoutSpin);

    // Keep Alive
    m_keepAliveCheck = new QCheckBox("Enable keep alive packets", this);
    m_keepAliveCheck->setChecked(true);
    connect(m_keepAliveCheck, SIGNAL(toggled(bool)), this, SLOT(onAdvancedSettingsChanged()));
    formLayout->addRow("Keep Alive:", m_keepAliveCheck);

    // Keep Alive 间隔
    m_keepAliveIntervalSpin = new QSpinBox(this);
    m_keepAliveIntervalSpin->setRange(10, 300);
    m_keepAliveIntervalSpin->setValue(30);
    m_keepAliveIntervalSpin->setSuffix(" seconds");
    formLayout->addRow("Keep Alive Interval:", m_keepAliveIntervalSpin);

    // 压缩
    m_compressionCheck = new QCheckBox("Enable compression", this);
    formLayout->addRow("Compression:", m_compressionCheck);

    // 终端类型
    m_terminalTypeCombo = new QComboBox(this);
    m_terminalTypeCombo->addItems(QStringList() << "xterm-256color" << "xterm" << "vt100" << "vt220" << "ansi");
    formLayout->addRow("Terminal Type:", m_terminalTypeCombo);

    advancedLayout->addLayout(formLayout);
    advancedLayout->addStretch();

    m_tabWidget->addTab(advancedWidget, "Advanced");
}

void ConfigDialog::createTerminalSettingsTab()
{
    QWidget *terminalWidget = new QWidget();
    QVBoxLayout *terminalLayout = new QVBoxLayout(terminalWidget);

    QFormLayout *formLayout = new QFormLayout();

    // 字体
    m_fontCombo = new QFontComboBox(this);
    m_fontCombo->setCurrentFont(QFont("Consolas"));
    formLayout->addRow("Font:", m_fontCombo);

    // 字体大小
    m_fontSizeSpin = new QSpinBox(this);
    m_fontSizeSpin->setRange(6, 72);
    m_fontSizeSpin->setValue(10);
    formLayout->addRow("Font Size:", m_fontSizeSpin);

    // 透明度
    QHBoxLayout *transparencyLayout = new QHBoxLayout();
    m_transparencySlider = new QSlider(Qt::Horizontal, this);
    m_transparencySlider->setRange(0, 100);
    m_transparencySlider->setValue(100);
    m_transparencyValueLabel = new QLabel("100%", this);
    transparencyLayout->addWidget(m_transparencySlider);
    transparencyLayout->addWidget(m_transparencyValueLabel);
    formLayout->addRow("Transparency:", transparencyLayout);

    // 终端响铃
    m_bellCheck = new QCheckBox("Enable terminal bell", this);
    formLayout->addRow("Bell:", m_bellCheck);

    // 光标闪烁
    m_cursorBlinkCheck = new QCheckBox("Enable cursor blinking", this);
    m_cursorBlinkCheck->setChecked(true);
    formLayout->addRow("Cursor Blink:", m_cursorBlinkCheck);

    // 光标形状
    m_cursorShapeCombo = new QComboBox(this);
    m_cursorShapeCombo->addItems(QStringList() << "Block" << "Underline" << "Vertical Bar");
    formLayout->addRow("Cursor Shape:", m_cursorShapeCombo);

    // 回滚行数
    m_scrollbackSpin = new QSpinBox(this);
    m_scrollbackSpin->setRange(100, 10000);
    m_scrollbackSpin->setValue(1000);
    m_scrollbackSpin->setSingleStep(100);
    formLayout->addRow("Scrollback Lines:", m_scrollbackSpin);

    // 自动换行
    m_wordWrapCheck = new QCheckBox("Enable word wrap", this);
    formLayout->addRow("Word Wrap:", m_wordWrapCheck);

    // 替代屏幕
    m_altScreenCheck = new QCheckBox("Enable alternate screen", this);
    m_altScreenCheck->setChecked(true);
    formLayout->addRow("Alternate Screen:", m_altScreenCheck);

    terminalLayout->addLayout(formLayout);
    terminalLayout->addStretch();

    m_tabWidget->addTab(terminalWidget, "Terminal");
}

void ConfigDialog::createAppearanceSettingsTab()
{
    QWidget *appearanceWidget = new QWidget();
    QVBoxLayout *appearanceLayout = new QVBoxLayout(appearanceWidget);

    // 颜色设置组
    QGroupBox *colorGroup = new QGroupBox("Colors", this);
    QGridLayout *colorLayout = new QGridLayout(colorGroup);

    // 前景色和背景色
    colorLayout->addWidget(new QLabel("Foreground:"), 0, 0);
    m_fgColorButton = new QPushButton(this);
    m_fgColorButton->setFixedSize(50, 20);
    setColorButtonColor(m_fgColorButton, Qt::white);
    connect(m_fgColorButton, SIGNAL(clicked()), this, SLOT(onColorButtonClicked()));
    colorLayout->addWidget(m_fgColorButton, 0, 1);

    colorLayout->addWidget(new QLabel("Background:"), 0, 2);
    m_bgColorButton = new QPushButton(this);
    m_bgColorButton->setFixedSize(50, 20);
    setColorButtonColor(m_bgColorButton, Qt::black);
    connect(m_bgColorButton, SIGNAL(clicked()), this, SLOT(onColorButtonClicked()));
    colorLayout->addWidget(m_bgColorButton, 0, 3);

    // 光标颜色
    colorLayout->addWidget(new QLabel("Cursor:"), 1, 0);
    m_cursorColorButton = new QPushButton(this);
    m_cursorColorButton->setFixedSize(50, 20);
    setColorButtonColor(m_cursorColorButton, Qt::green);
    connect(m_cursorColorButton, SIGNAL(clicked()), this, SLOT(onColorButtonClicked()));
    colorLayout->addWidget(m_cursorColorButton, 1, 1);

    // 选择颜色
    colorLayout->addWidget(new QLabel("Selection:"), 1, 2);
    m_selectionColorButton = new QPushButton(this);
    m_selectionColorButton->setFixedSize(50, 20);
    setColorButtonColor(m_selectionColorButton, QColor(100, 100, 255));
    connect(m_selectionColorButton, SIGNAL(clicked()), this, SLOT(onColorButtonClicked()));
    colorLayout->addWidget(m_selectionColorButton, 1, 3);

    // ANSI颜色
    QGroupBox *ansiGroup = new QGroupBox("ANSI Colors", this);
    QGridLayout *ansiLayout = new QGridLayout(ansiGroup);

    QStringList colorNames = {"Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"};
    QList<QPushButton*> normalButtons = {
        m_blackColorButton = new QPushButton,
        m_redColorButton = new QPushButton,
        m_greenColorButton = new QPushButton,
        m_yellowColorButton  = new QPushButton,
        m_blueColorButton  = new QPushButton,
        m_magentaColorButton = new QPushButton,
        m_cyanColorButton = new QPushButton,
        m_whiteColorButton = new QPushButton
    };

    QList<QPushButton*> brightButtons = {
        m_brightBlackColorButton  = new QPushButton,
        m_brightRedColorButton  = new QPushButton,
        m_brightGreenColorButton  = new QPushButton,
        m_brightYellowColorButton  = new QPushButton,
        m_brightBlueColorButton  = new QPushButton,
        m_brightMagentaColorButton  = new QPushButton,
        m_brightCyanColorButton  = new QPushButton,
        m_brightWhiteColorButton  = new QPushButton
    };

    for (int i = 0; i < 8; i++) {
        // 标签
        ansiLayout->addWidget(new QLabel(colorNames[i] + ":"), i, 0);

        // 正常颜色
        QPushButton *normalBtn = normalButtons[i];
        normalBtn->setFixedSize(50, 20);
        setColorButtonColor(normalBtn, QColor(i == 0 ? 0 : (i == 1 ? 255 : (i == 2 ? 0 : 255)),
                                           i == 3 ? 255 : (i == 4 ? 0 : (i == 5 ? 255 : 0)),
                                           i == 6 ? 255 : (i == 7 ? 255 : 0)));
        ansiLayout->addWidget(normalBtn, i, 1);

        // 亮色
        QPushButton *brightBtn = brightButtons[i];
        brightBtn->setFixedSize(50, 20);
        setColorButtonColor(brightBtn, QColor(i == 0 ? 128 : (i == 1 ? 255 : (i == 2 ? 128 : 255)),
                                            i == 3 ? 255 : (i == 4 ? 128 : (i == 5 ? 255 : 128)),
                                            i == 6 ? 255 : (i == 7 ? 255 : 128)));
        ansiLayout->addWidget(brightBtn, i, 2);
    }

    appearanceLayout->addWidget(colorGroup);
    appearanceLayout->addWidget(ansiGroup);
    appearanceLayout->addStretch();

    m_tabWidget->addTab(appearanceWidget, "Appearance");
}

void ConfigDialog::createButtons()
{
    m_testButton = new QPushButton("Test Connection", this);
    connect(m_testButton, SIGNAL(clicked()), this, SLOT(testConnection()));

    m_resetButton = new QPushButton("Reset", this);
    connect(m_resetButton, SIGNAL(clicked()), this, SLOT(resetToDefaults()));

    m_saveButton = new QPushButton("Save", this);
    m_saveButton->setDefault(true);
    connect(m_saveButton, SIGNAL(clicked()), this, SLOT(saveProfile()));

    m_cancelButton = new QPushButton("Cancel", this);
    connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}

QHBoxLayout *ConfigDialog::createButtonsLayout()
{
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    buttonLayout->addWidget(m_testButton);
    buttonLayout->addWidget(m_resetButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_saveButton);
    buttonLayout->addWidget(m_cancelButton);

    return buttonLayout;
}

void ConfigDialog::loadSettings()
{
    // 加载默认设置
    resetSettings();
}

void ConfigDialog::saveSettings()
{
    // 保存设置到QSettings
}

void ConfigDialog::resetSettings()
{
    // 重置所有字段到默认值
    m_nameEdit->clear();
    m_hostEdit->clear();
    m_portSpin->setValue(22);
    m_usernameEdit->clear();
    m_passwordEdit->clear();
    m_privateKeyEdit->clear();
    m_passphraseEdit->clear();
    m_descriptionEdit->clear();
    m_groupCombo->setCurrentText("Default");
    m_favoriteCheck->setChecked(false);

    updateAuthMethodUI();
}

void ConfigDialog::updateGroupCombo()
{
    // 更新组下拉框
}

void ConfigDialog::updateAuthMethodUI()
{
    QString method = m_authMethodCombo->currentText();

    // 根据认证方法启用/禁用相关字段
    if (method == "Password") {
        m_passwordEdit->setEnabled(true);
        m_privateKeyEdit->setEnabled(false);
        m_browseKeyButton->setEnabled(false);
        m_passphraseEdit->setEnabled(false);
    } else if (method == "Public Key") {
        m_passwordEdit->setEnabled(false);
        m_privateKeyEdit->setEnabled(true);
        m_browseKeyButton->setEnabled(true);
        m_passphraseEdit->setEnabled(true);
    } else if (method == "SSH Agent") {
        m_passwordEdit->setEnabled(false);
        m_privateKeyEdit->setEnabled(false);
        m_browseKeyButton->setEnabled(false);
        m_passphraseEdit->setEnabled(false);
    }
}

void ConfigDialog::setColorButtonColor(QPushButton *button, const QColor &color)
{
    QString style = QString("background-color: %1; border: 1px solid black;").arg(color.name());
    button->setStyleSheet(style);
}

QColor ConfigDialog::getColorFromButton(QPushButton *button) const
{
    // 从按钮样式提取颜色
    QString style = button->styleSheet();
    QRegularExpression regex("background-color:\\s*([^;]+);");
    QRegularExpressionMatch match = regex.match(style);
    if (match.hasMatch()) {
        return QColor(match.captured(1).trimmed());
    }
    return Qt::black;
}

bool ConfigDialog::validateBasicSettings() const
{
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(nullptr, "Validation Error", "Profile name cannot be empty");
        m_nameEdit->setFocus();
        return false;
    }

    if (m_hostEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(nullptr, "Validation Error", "Host address cannot be empty");
        m_hostEdit->setFocus();
        return false;
    }

    if (m_usernameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(nullptr, "Validation Error", "Username cannot be empty");
        m_usernameEdit->setFocus();
        return false;
    }

    if (m_authMethodCombo->currentText() == "Password" && m_passwordEdit->text().isEmpty()) {
        QMessageBox::warning(nullptr, "Validation Error", "Password cannot be empty for password authentication");
        m_passwordEdit->setFocus();
        return false;
    }

    if (m_authMethodCombo->currentText() == "Public Key" && m_privateKeyEdit->text().isEmpty()) {
        QMessageBox::warning(nullptr, "Validation Error", "Private key file cannot be empty for public key authentication");
        m_privateKeyEdit->setFocus();
        return false;
    }

    return true;
}

bool ConfigDialog::validateAdvancedSettings() const
{
    return true;
}

bool ConfigDialog::validateTerminalSettings() const
{
    return true;
}

bool ConfigDialog::validateAppearanceSettings() const
{
    return true;
}

bool ConfigDialog::testConnectionInternal(const ConnectionManager::ConnectionProfile &profile)
{
    // 内部连接测试逻辑
    // 这里应该尝试建立测试连接
    showTestResult(true, "Connection test successful");
    return true;
}

void ConfigDialog::showTestResult(bool success, const QString &message)
{
    if (success) {
        QMessageBox::information(this, "Test Result", message);
    } else {
        QMessageBox::warning(this, "Test Result", message);
    }
}

QString ConfigDialog::encryptPassword(const QString &password) const
{
    // 简单的密码加密（实际应用中应该使用更安全的方法）
    return password; // 临时实现
}

QString ConfigDialog::decryptPassword(const QString &encrypted) const
{
    // 简单的密码解密
    return encrypted; // 临时实现
}

void ConfigDialog::showError(const QString &title, const QString &message)
{
    QMessageBox::critical(this, title, message);
}

void ConfigDialog::showInfo(const QString &title, const QString &message)
{
    QMessageBox::information(this, title, message);
}

void ConfigDialog::showWarning(const QString &title, const QString &message)
{
    QMessageBox::warning(this, title, message);
}

void ConfigDialog::onColorButtonClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) {
        return;
    }

    QColor currentColor = getColorFromButton(button);
    QColor color = QColorDialog::getColor(currentColor, this, "Select Color");

    if (color.isValid()) {
        setColorButtonColor(button, color);
    }
}
